<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>NAGA 文档上传系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 25px 50px rgba(0,0,0,0.15);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 40px 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.8em;
            margin-bottom: 15px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
            letter-spacing: 1px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
            line-height: 1.5;
            margin-top: 10px;
        }

        .content {
            padding: 50px 40px;
        }

        .upload-section {
            margin-bottom: 50px;
        }

        .upload-area {
            border: 3px dashed #4facfe;
            border-radius: 15px;
            padding: 60px 40px;
            text-align: center;
            background: #f8f9ff;
            transition: all 0.3s ease;
            cursor: pointer;
            margin-bottom: 30px;
        }

        .upload-area:hover {
            border-color: #00f2fe;
            background: #f0f4ff;
        }

        .upload-area.dragover {
            border-color: #00f2fe;
            background: #e6f3ff;
            transform: scale(1.02);
        }

        .upload-icon {
            font-size: 4em;
            color: #4facfe;
            margin-bottom: 25px;
            line-height: 1;
        }

        .upload-text {
            font-size: 1.3em;
            color: #666;
            margin-bottom: 20px;
            line-height: 1.4;
            font-weight: 500;
        }

        .file-input {
            display: none;
        }

        .btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 15px 35px;
            border-radius: 30px;
            font-size: 1.1em;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 8px 10px;
            letter-spacing: 0.5px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
        }

        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .file-info {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 30px;
            margin: 30px 0;
            display: none;
            border: 1px solid #e9ecef;
        }

        .file-info.show {
            display: block;
        }

        .action-buttons {
            margin-top: 30px;
            text-align: center;
        }

        .result-area {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 30px;
            margin-top: 30px;
            display: none;
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid #e9ecef;
            line-height: 1.6;
        }

        .result-area.show {
            display: block;
        }

        .loading {
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #4facfe;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .error {
            color: #e74c3c;
            background: #fdf2f2;
            border: 1px solid #f5c6cb;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }

        .success {
            color: #27ae60;
            background: #f2f8f2;
            border: 1px solid #c3e6cb;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }

        .document-list {
            margin-top: 50px;
            padding-top: 30px;
            border-top: 2px solid #e9ecef;
        }

        .document-item {
            background: #f8f9fa;
            border-radius: 12px;
            padding: 20px;
            margin: 15px 0;
            border-left: 5px solid #4facfe;
            transition: all 0.3s ease;
        }
        
        .document-item:hover {
            background: #f0f4ff;
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.1);
        }

        .document-name {
            font-weight: 600;
            color: #333;
            font-size: 1.1em;
            margin-bottom: 8px;
        }

        .document-meta {
            color: #666;
            font-size: 0.95em;
            line-height: 1.4;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 NAGA 文档处理系统</h1>
            <p>上传您的文档，让研天雪为您智能分析和处理</p>
        </div>
        
        <div class="content">
            <div class="upload-section">
                <div class="upload-area" id="uploadArea">
                    <div class="upload-icon">📄</div>
                    <div class="upload-text">拖拽文件到此处或点击选择文件</div>
                    <div style="color: #999; font-size: 0.9em;">支持格式: .docx, .doc, .txt, .pdf, .md</div>
                    <input type="file" id="fileInput" class="file-input" accept=".docx,.doc,.txt,.pdf,.md">
                </div>
                
                <div class="file-info" id="fileInfo">
                    <h3>📋 文件信息</h3>
                    <div id="fileDetails"></div>
                    <div class="action-buttons">
                        <button class="btn" onclick="processDocument('read')">📖 读取内容</button>
                        <button class="btn" onclick="processDocument('analyze')">🔍 智能分析</button>
                        <button class="btn" onclick="processDocument('summarize')">📝 生成摘要</button>
                    </div>
                </div>
                
                <div class="result-area" id="resultArea">
                    <h3 id="resultTitle">处理结果</h3>
                    <div id="resultContent"></div>
                </div>
            </div>
            
            <div class="document-list">
                <h3>📚 已上传的文档</h3>
                <button class="btn" onclick="loadDocumentList()">🔄 刷新列表</button>
                <div id="documentList"></div>
            </div>
        </div>
    </div>

    <script>
        let currentFilePath = null;
        const API_BASE = 'http://localhost:8000';

        // 初始化
        document.addEventListener('DOMContentLoaded', function() {
            setupEventListeners();
            loadDocumentList();
        });

        function setupEventListeners() {
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');

            // 点击上传区域
            uploadArea.addEventListener('click', () => fileInput.click());

            // 文件选择
            fileInput.addEventListener('change', handleFileSelect);

            // 拖拽事件
            uploadArea.addEventListener('dragover', handleDragOver);
            uploadArea.addEventListener('dragleave', handleDragLeave);
            uploadArea.addEventListener('drop', handleDrop);
        }

        function handleDragOver(e) {
            e.preventDefault();
            document.getElementById('uploadArea').classList.add('dragover');
        }

        function handleDragLeave(e) {
            e.preventDefault();
            document.getElementById('uploadArea').classList.remove('dragover');
        }

        function handleDrop(e) {
            e.preventDefault();
            document.getElementById('uploadArea').classList.remove('dragover');
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                uploadFile(files[0]);
            }
        }

        function handleFileSelect(e) {
            const file = e.target.files[0];
            if (file) {
                uploadFile(file);
            }
        }

        async function uploadFile(file) {
            const formData = new FormData();
            formData.append('file', file);

            try {
                showLoading('正在上传文件...');
                
                const response = await fetch(`${API_BASE}/upload/document`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (response.ok) {
                    showSuccess(result.message);
                    showFileInfo(result);
                    currentFilePath = result.file_path;
                    loadDocumentList();
                } else {
                    showError(result.detail || '上传失败');
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        function showFileInfo(fileData) {
            const fileInfo = document.getElementById('fileInfo');
            const fileDetails = document.getElementById('fileDetails');
            
            fileDetails.innerHTML = `
                <p><strong>文件名:</strong> ${fileData.filename}</p>
                <p><strong>文件大小:</strong> ${formatFileSize(fileData.file_size)}</p>
                <p><strong>文件类型:</strong> ${fileData.file_type}</p>
                <p><strong>上传时间:</strong> ${fileData.upload_time}</p>
            `;
            
            fileInfo.classList.add('show');
        }

        async function processDocument(action) {
            if (!currentFilePath) {
                showError('请先上传文件');
                return;
            }

            try {
                showLoading(`正在${getActionName(action)}...`);
                
                const response = await fetch(`${API_BASE}/document/process`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        file_path: currentFilePath,
                        action: action
                    })
                });

                const result = await response.json();
                
                if (response.ok) {
                    showResult(action, result);
                } else {
                    showError(result.detail || '处理失败');
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        function getActionName(action) {
            const names = {
                'read': '读取文档内容',
                'analyze': '分析文档',
                'summarize': '生成摘要'
            };
            return names[action] || action;
        }

        function showResult(action, result) {
            const resultArea = document.getElementById('resultArea');
            const resultTitle = document.getElementById('resultTitle');
            const resultContent = document.getElementById('resultContent');
            
            resultTitle.textContent = `📊 ${getActionName(action)}结果`;
            
            let content = '';
            if (action === 'read') {
                content = `<pre style="white-space: pre-wrap; word-wrap: break-word;">${result.content}</pre>`;
            } else if (action === 'analyze') {
                content = `<div style="line-height: 1.6;">${result.analysis}</div>`;
            } else if (action === 'summarize') {
                content = `<div style="line-height: 1.6;">${result.summary}</div>`;
            }
            
            resultContent.innerHTML = content;
            resultArea.classList.add('show');
        }

        async function loadDocumentList() {
            try {
                const response = await fetch(`${API_BASE}/documents/list`);
                const result = await response.json();
                
                if (response.ok) {
                    displayDocumentList(result.documents);
                } else {
                    showError('获取文档列表失败');
                }
            } catch (error) {
                showError('网络错误: ' + error.message);
            }
        }

        function displayDocumentList(documents) {
            const documentList = document.getElementById('documentList');
            
            if (documents.length === 0) {
                documentList.innerHTML = '<p style="color: #999; text-align: center; padding: 20px;">暂无上传的文档</p>';
                return;
            }
            
            const html = documents.map(doc => `
                <div class="document-item">
                    <div class="document-name">${doc.filename}</div>
                    <div class="document-meta">
                        大小: ${formatFileSize(doc.file_size)} | 
                        类型: ${doc.file_type} | 
                        上传时间: ${doc.upload_time}
                    </div>
                </div>
            `).join('');
            
            documentList.innerHTML = html;
        }

        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        function showLoading(message) {
            const resultArea = document.getElementById('resultArea');
            const resultContent = document.getElementById('resultContent');
            
            resultContent.innerHTML = `
                <div class="loading">
                    <div class="spinner"></div>
                    <div>${message}</div>
                </div>
            `;
            
            resultArea.classList.add('show');
        }

        function hideLoading() {
            // Loading will be replaced by result content
        }

        function showError(message) {
            const resultArea = document.getElementById('resultArea');
            const resultContent = document.getElementById('resultContent');
            
            resultContent.innerHTML = `<div class="error">❌ ${message}</div>`;
            resultArea.classList.add('show');
        }

        function showSuccess(message) {
            const resultArea = document.getElementById('resultArea');
            const resultContent = document.getElementById('resultContent');
            
            resultContent.innerHTML = `<div class="success">✅ ${message}</div>`;
            resultArea.classList.add('show');
        }
    </script>
</body>
</html>